'use client';

import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Container,
  Paper,
  TextField,
  Button,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormHelperText,
  Alert,
  CircularProgress,
  Breadcrumbs,
  Divider,
  Chip,
} from '@mui/material';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import BusinessIcon from '@mui/icons-material/Business';
import WorkIcon from '@mui/icons-material/Work';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import SchoolIcon from '@mui/icons-material/School';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

// 教育程度选项
const educationOptions = [
  '不限',
  '高中',
  '大专',
  '本科',
  '硕士',
  '博士',
];

// 工作经验选项
const experienceOptions = [
  '不限',
  '应届毕业生',
  '1年以下',
  '1-3年',
  '3-5年',
  '5-10年',
  '10年以上',
];

// 工作类型选项
const jobTypeOptions = [
  '全职',
  '兼职',
  '实习',
  '校招',
  '社招',
];

export default function PostJobPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [isCompanyAdmin, setIsCompanyAdmin] = useState(false);
  const [companyInfo, setCompanyInfo] = useState<any>(null);
  const [formData, setFormData] = useState({
    title: '',
    company_id: '',
    description: '',
    requirements: '',
    salary_range: '',
    location: '',
    job_type: '全职',
    experience: '不限',
    education: '不限',
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // 检查用户是否为企业负责人
  useEffect(() => {
    const checkCompanyAdmin = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          router.push('/auth/login');
          return;
        }

        const response = await fetch('/api/profile', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (!response.ok) {
          throw new Error('获取用户信息失败');
        }

        const userData = await response.json();
        const isAdmin = userData.is_company_admin || false;
        setIsCompanyAdmin(isAdmin);

        if (!isAdmin) {
          // 如果不是企业负责人，跳转到招聘页面
          router.push('/recruitment');
          return;
        }

        // 获取企业信息
        try {
          const companyResponse = await fetch('/api/company/info', {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          });

          if (companyResponse.ok) {
            const companyData = await companyResponse.json();
            setCompanyInfo(companyData);

            // 预填表单
            setFormData(prev => ({
              ...prev,
              company_id: companyData.id?.toString() || '',
              location: userData.location || '',
            }));
          } else {
            // 如果获取企业信息失败，使用默认值
            setCompanyInfo({
              name: userData.company || (userData.username + '的公司'),
              admin_user_id: userData.id
            });
          }
        } catch (err) {
          console.error('获取企业信息失败:', err);
          // 如果获取企业信息失败，使用默认值
          setCompanyInfo({
            name: userData.company || (userData.username + '的公司'),
            admin_user_id: userData.id
          });
        }
      } catch (err) {
        setError((err as Error).message);
      }
    };

    checkCompanyAdmin();
  }, [router]);

  // 处理表单变化
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));

    // 清除对应字段的错误
    if (formErrors[name]) {
      setFormErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  // 处理选择框变化
  const handleSelectChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));

    // 清除对应字段的错误
    if (formErrors[name]) {
      setFormErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  // 验证表单
  const validateForm = () => {
    const errors: Record<string, string> = {};

    if (!formData.title.trim()) {
      errors.title = '职位名称不能为空';
    }

    if (!formData.description.trim()) {
      errors.description = '职位描述不能为空';
    }

    if (!formData.requirements.trim()) {
      errors.requirements = '职位要求不能为空';
    }

    if (!formData.salary_range.trim()) {
      errors.salary_range = '薪资范围不能为空';
    }

    if (!formData.location.trim()) {
      errors.location = '工作地点不能为空';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const response = await fetch('/api/recruitment/post-job', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '发布招聘公告失败');
      }

      setSuccess(true);

      // 3秒后跳转到招聘页面
      setTimeout(() => {
        router.push('/recruitment');
      }, 3000);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  // 如果不是企业负责人，显示加载中
  if (!isCompanyAdmin && !error) {
    return (
      <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
        <Container maxWidth="lg" sx={{ py: 4 }}>
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
            <CircularProgress />
          </Box>
        </Container>
      </Box>
    );
  }

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>

      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box sx={{ mb: 4 }}>
          <Breadcrumbs aria-label="breadcrumb">
            <Link href="/" passHref>
              <Typography color="inherit" sx={{ display: 'flex', alignItems: 'center' }}>
                首页
              </Typography>
            </Link>
            <Link href="/recruitment" passHref>
              <Typography color="inherit" sx={{ display: 'flex', alignItems: 'center' }}>
                企业招聘直通车
              </Typography>
            </Link>
            <Typography color="text.primary">发布招聘公告</Typography>
          </Breadcrumbs>
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h5" component="h1">
            发布招聘公告
          </Typography>
          <Button
            variant="outlined"
            startIcon={<ArrowBackIcon />}
            onClick={() => router.push('/recruitment')}
          >
            返回
          </Button>
        </Box>

        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 3 }}>
            招聘公告发布成功！3秒后将跳转到招聘页面...
          </Alert>
        )}

        <Paper sx={{ p: 3, mb: 4 }}>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              企业信息
            </Typography>
            <Divider sx={{ mb: 2 }} />

            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <BusinessIcon color="primary" sx={{ mr: 1 }} />
                  <Typography variant="body1">
                    {companyInfo?.name || '您的企业'}
                  </Typography>
                </Box>
              </Grid>
              {companyInfo?.industry && (
                <Grid item xs={12} sm={6}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <WorkIcon color="primary" sx={{ mr: 1 }} />
                    <Typography variant="body1">
                      {companyInfo.industry}
                    </Typography>
                  </Box>
                </Grid>
              )}
            </Grid>
          </Box>

          <Box component="form" onSubmit={handleSubmit}>
            <Typography variant="h6" gutterBottom>
              职位信息
            </Typography>
            <Divider sx={{ mb: 2 }} />

            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="职位名称"
                  name="title"
                  value={formData.title}
                  onChange={handleChange}
                  required
                  error={!!formErrors.title}
                  helperText={formErrors.title}
                  disabled={loading || success}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="工作地点"
                  name="location"
                  value={formData.location}
                  onChange={handleChange}
                  required
                  error={!!formErrors.location}
                  helperText={formErrors.location}
                  disabled={loading || success}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="薪资范围"
                  name="salary_range"
                  value={formData.salary_range}
                  onChange={handleChange}
                  placeholder="例如：15k-25k"
                  required
                  error={!!formErrors.salary_range}
                  helperText={formErrors.salary_range}
                  disabled={loading || success}
                />
              </Grid>

              <Grid item xs={12} sm={4}>
                <FormControl fullWidth>
                  <InputLabel>工作类型</InputLabel>
                  <Select
                    name="job_type"
                    value={formData.job_type}
                    onChange={handleSelectChange}
                    label="工作类型"
                    disabled={loading || success}
                  >
                    {jobTypeOptions.map(option => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12} sm={4}>
                <FormControl fullWidth>
                  <InputLabel>工作经验</InputLabel>
                  <Select
                    name="experience"
                    value={formData.experience}
                    onChange={handleSelectChange}
                    label="工作经验"
                    disabled={loading || success}
                  >
                    {experienceOptions.map(option => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12} sm={4}>
                <FormControl fullWidth>
                  <InputLabel>学历要求</InputLabel>
                  <Select
                    name="education"
                    value={formData.education}
                    onChange={handleSelectChange}
                    label="学历要求"
                    disabled={loading || success}
                  >
                    {educationOptions.map(option => (
                      <MenuItem key={option} value={option}>
                        {option}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="职位描述"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  multiline
                  rows={4}
                  required
                  error={!!formErrors.description}
                  helperText={formErrors.description}
                  disabled={loading || success}
                />
              </Grid>

              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="职位要求"
                  name="requirements"
                  value={formData.requirements}
                  onChange={handleChange}
                  multiline
                  rows={4}
                  required
                  error={!!formErrors.requirements}
                  helperText={formErrors.requirements}
                  disabled={loading || success}
                />
              </Grid>

              <Grid item xs={12}>
                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
                  <Button
                    type="button"
                    variant="outlined"
                    onClick={() => router.push('/recruitment')}
                    sx={{ mr: 2 }}
                    disabled={loading || success}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    disabled={loading || success}
                    startIcon={loading && <CircularProgress size={20} />}
                  >
                    {loading ? '发布中...' : '发布招聘公告'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </Box>
        </Paper>
      </Container>
    </Box>
  );
}
